/**
 * 
 */
package com.cmcc.pcap.packet.sctp;

import com.cmcc.pcap.packet.tcp.TcpConnectionCache;
import com.cmcc.pcap.packet.tcp.TcpPacketDecorator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.pcap4j.packet.IpPacket;
import org.pcap4j.packet.SctpPacket;
import org.pcap4j.packet.TcpPacket;
import org.pcap4j.packet.namednumber.SctpChunkType;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @Date 2018年4月19日 下午3:29:10
 * @author Amish
 */
public class SctpProducer implements Runnable{
	private static Logger logger = LogManager.getLogger(SctpProducer.class);

     private IpPacket ipPacket;
     private SctpConnectionCache sctpConnectionCache;
     private Timestamp timestamp;


     public SctpProducer(IpPacket ipPacket, SctpConnectionCache sctpConnectionCache, Timestamp timestamp) {
    	 this.ipPacket = ipPacket;
    	 this.sctpConnectionCache = sctpConnectionCache;
    	 this.timestamp = timestamp;
     }
     
	@Override
	public void run() {
		try{
			SctpPacketDecorator sctpPacketDecorator;
			boolean isNINT = false;
			/*
			第一条SCTP消息，SCTP四次握手第一条消息，chunk type是INIT
			 */
			if(ipPacket.get(SctpPacket.class).getHeader().getChunks().size() == 1 && ipPacket.get(SctpPacket.class).getHeader().getChunks().get(0).getType() == SctpChunkType.INIT){
				logger.debug("receive the first sctp message : ");
				isNINT = true;
			}else{
				isNINT = false;
			}

			sctpPacketDecorator = new SctpPacketDecorator(isNINT);

			sctpPacketDecorator.sctpPacket = ipPacket.get(SctpPacket.class);
			sctpPacketDecorator.ipPacket = ipPacket;
			sctpPacketDecorator.timestamp = this.timestamp;
			sctpPacketDecorator.chunklist = sctpPacketDecorator.sctpPacket.getHeader().getChunks();
			sctpPacketDecorator.chunktypelist = new ArrayList<SctpChunkType>();

			for(SctpPacket.SctpChunk chunk : sctpPacketDecorator.chunklist){
				sctpPacketDecorator.chunktypelist.add(chunk.getType());
			}

			this.sctpConnectionCache.addSctpPacketDecorator(sctpPacketDecorator);
		}catch(Exception e){
			logger.error("SctpHandler has some exception : ",e);
		}
	}

}
